package com.briup.prs;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.KeyValueLineRecordReader;
import org.apache.hadoop.mapreduce.lib.input.KeyValueTextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

import java.io.IOException;

/**
 * @author adam
 * @date 2022/2/8
 */
public class Step5 extends Configured implements Tool {

    public static class S5Mapper extends Mapper<Text,Text,Text,Text>{
        @Override
//        key=商品A:商品B   value=次数
        protected void map(Text key, Text value, Context context) throws IOException, InterruptedException {
            String[] data = key.toString().split(":");
           Text oKey=new Text(data[0]) ;
           Text oValue=new Text(data[1]+":"+value);
//           key=商品A   value=商品B:次数
           context.write(oKey,oValue);

        }
    }
    public static class S5Reducer extends Reducer<Text,Text,Text,Text>{
        @Override
        protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
            StringBuilder sb=new StringBuilder();
            for (Text value : values) {
              sb.append(value.toString()).append(",");
            }
            String str=sb.substring(0,sb.length()-1);
            context.write(key,new Text(str));
        }
    }
    @Override
    public int run(String[] strings) throws Exception {
        Configuration conf = getConf();
        //设置分隔符
        conf.set(KeyValueLineRecordReader.KEY_VALUE_SEPARATOR,"\t");
        Job job = Job.getInstance(conf,"Step5");
        job.setJarByClass(Step5.class);

        job.setInputFormatClass(KeyValueTextInputFormat.class);
        KeyValueTextInputFormat.addInputPath(job,
                new Path("src/main/resources/step4"));

        job.setMapperClass(S5Mapper.class);
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(Text.class);

        job.setReducerClass(S5Reducer.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);

        job.setOutputFormatClass(TextOutputFormat.class);
        TextOutputFormat.setOutputPath(job,
                new Path("src/main/resources/step5"));

        job.waitForCompletion(true);

        return 0;
    }

    public static void main(String[] args) throws Exception {
        ToolRunner.run(new Step5(),args);
    }
}
